package client;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.JTextArea;


/**********************************************************
 * GROUP : HONEYBADGER
 * DEVELOPER: CHRISTOPHER CONRY, TYLER HERZOG
 * CLIENTLISTENER: THIS IS USED TO HANDLE ALL EVENTS FROM BUTTONS.
 * INCLUDING CONNECT, CONNECT LOCAL AND SUBMIT
 *********************************************************/
public class Clientlistener extends Thread {
	String message;
	BufferedReader in;
	JTextArea Textarea;
	/**********************************************************
	 * GROUP : HONEYBADGER
	 * DEVELOPER: CHRISTOPHER CONRY, TYLER HERZOG
	 * CLIENTLISTENER.CONSTRUCTOR: TO CREATE A CLIENTLISTENER AND TO 
	 * TAKE IN THE DATA INPUT STREAM AND WHERE TO WRITE DATA
	 *********************************************************/
	Clientlistener(DataInputStream in_p, JTextArea TA) {
		in = new BufferedReader(new InputStreamReader(in_p));
		Textarea = TA;
	}
	
	/**********************************************************
	 * GROUP : HONEYBADGER
	 * DEVELOPER: CHRISTOPHER CONRY, TYLER HERZOG
	 * RUN: THIS IS THE PART THAT LISTENS FOR INCOMMING MESSAGES AND PROCESSES THEM.
	 *********************************************************/
	public void run() {
		try {
			try {
				while (true) {
					message = in.readLine();
					Textarea.append(message + "\n");
					if (message.startsWith("ourHTTP/1.0 200 Document Follows")) {
						String toBeDownloaded = message.substring(
								(message.indexOf("Content-type: ") + 14),
								message.indexOf(" \n Content_length"));
						File dl = new File("cache/" + toBeDownloaded);
						message = in.readLine();
						FileWriter oput = new FileWriter(dl);
						oput.write(message);
						oput.close();
						Textarea.append(toBeDownloaded + " Downloaded");

					}
				}
			} catch (EOFException except) {
			}
		} catch (IOException except) {
		}
	}
	/**********************************************************
	 * GROUP : HONEYBADGER
	 * DEVELOPER: CHRISTOPHER CONRY, TYLER HERZOG
	 * KILL: ALLOWS THE THREAD TO BE KILLED PUBLICLY.
	 *********************************************************/
	public void kill() {
		this.kill();
	}
}
